package com.ysstech.kettle.controller;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ysstech.common.annotation.YssLog;
import com.ysstech.common.annotation.YssPermissions;
import com.ysstech.common.controller.BaseController;
import com.ysstech.common.exception.BusinessException;
import com.ysstech.common.util.DateUtil;
import com.ysstech.common.util.JsonUtil;
import com.ysstech.common.util.resultutil.RestResult;
import com.ysstech.common.util.resultutil.ResultGenerator;
import com.ysstech.kettle.entity.*;
import com.ysstech.kettle.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author lishuangliang
 * @since 2022-10-11
 */
@Controller
@Slf4j
@Api(tags = "作业任务api")
@RequestMapping("/jobTask")
public class JobTaskController extends BaseController {

    @Autowired
    private JobTaskService jobTaskService;
    @Autowired
    private JobTaskDetailsService jobTaskDetailsService;
    @Autowired
    private JobCategoryService jobCategoryService;
    @Autowired
    private JobDatasourceService jobDatasourceService;
    @Autowired
    private JobRelationService jobRelationService;

    @YssPermissions(value = {"kettle:job:task"})
    @ApiOperation(value = "跳转作业任务管理页面")
    @YssLog(module = "作业任务管理", remark = "跳转作业任务管理页面")
    @RequestMapping(value = "/page")
    public String page() throws Exception {
        return "kettle/jobTask";
    }


    @YssPermissions(value = {"kettle:job:task"})
    @ApiOperation(value = "获取作业任务页面初始值")
    @YssLog(module = "作业任务管理", remark = "获取作业任务管理页面初始值")
    @PostMapping(value = "/init")
    @ResponseBody
    public RestResult init() throws Exception {
        Map<String, Object> map = new HashMap<>();
        //查询所有采集分类信息
        QueryWrapper<JobCategory> jobCategoryQueryWrapper = new QueryWrapper<>();
        jobCategoryQueryWrapper.eq("STATUS", 1);
        jobCategoryQueryWrapper.orderByAsc("SEQUENCE");
        List<JobCategory> jobCategorylist = jobCategoryService.list(jobCategoryQueryWrapper);
        map.put("jobCategorylist", jobCategorylist);
        map.put("jobCategorylist2", jobCategorylist);
        //获取所有数据库连接
        QueryWrapper<JobDatasource> jobDatasourceQueryWrapper = new QueryWrapper<>();
        jobDatasourceQueryWrapper.eq("STATUS", 1);
        List<JobDatasource> jobDatasourceList = jobDatasourceService.list(jobDatasourceQueryWrapper);
        map.put("jobDatasourceList", jobDatasourceList);
        return ResultGenerator.getSuccessResult("获取页面初始化信息成功", map);
    }

    @YssPermissions(value = {"kettle:job:task"})
    @ApiOperation(value = "更新任务关联关系")
    @YssLog(module = "作业任务管理", remark = "更新任务关联关系")
    @PostMapping(value = "/updateJobRelation")
    @ResponseBody
    public RestResult updateJobRelation() throws Exception {
        //更新关联关系
        List<JobTask> list = jobTaskService.list();
        if (CollectionUtils.isEmpty(list)) {
            return ResultGenerator.getSuccessResult("没有任务需要更新关联关系");
        }
        for (JobTask jobTask : list) {
            if (null == jobTask) {
                continue;
            }
            jobRelationService.insertJobRelation(jobTask);
        }
        return ResultGenerator.getSuccessResult("更新任务关联关系成功");
    }

    /**
     * 获取作业任务信息
     *
     * @return
     */
    @YssPermissions(value = {"kettle:job:task"})
    @ApiOperation(value = "获取作业任务信息")
    @YssLog(module = "作业任务管理", remark = "获取作业任务信息")
    @PostMapping(value = "/listInfo")
    @ResponseBody
    public RestResult listInfo(JobTask jobTask, String page, String rows) throws Exception {
        return ResultGenerator.getSuccessResult("获取作业任务信息成功",
                jobTaskService.queryAllJobTask(jobTask, this.getPage(page, rows)));
    }

    @YssPermissions(value = {"kettle:job:task"})
    @ApiOperation(value = "获取作业任务信息")
    @YssLog(module = "作业任务管理", remark = "获取作业任务信息")
    @PostMapping(value = "/queryCategoryJobTask")
    @ResponseBody
    public RestResult queryCategoryJobTask(JobTask jobTask) throws Exception {
        if (null == jobTask || StringUtils.isBlank(jobTask.getCategoryId())) {
            throw new BusinessException("获取任务信息出错，请稍后重试！");
        }
        // 每次都查询一个所有的采集任务下的作业任务
        QueryWrapper<JobTask> wrapper = new QueryWrapper<>();
        wrapper.eq("CATEGORY_ID", jobTask.getCategoryId());
        wrapper.eq("STATUS", 1);
        if(StringUtils.isNotBlank(jobTask.getName())){
            wrapper.like("NAME",jobTask.getName());
        }
        wrapper.orderByAsc("NAME");
        return ResultGenerator.getSuccessResult("获取作业任务信息成功", jobTaskService.list(wrapper));
    }

    @YssPermissions(value = {"kettle:job:task"})
    @ApiOperation(value = "获取作业任务信息")
    @YssLog(module = "作业任务管理", remark = "获取作业任务信息")
    @PostMapping(value = "/queryDutiesJobTask")
    @ResponseBody
    public RestResult queryDutiesJobTask(JobTask jobTask) throws Exception {
        if (null == jobTask || StringUtils.isBlank(jobTask.getCategoryId()) || StringUtils.isBlank(jobTask.getDutiesId())) {
            throw new BusinessException("获取任务信息出错，请稍后重试！");
        }
        return ResultGenerator.getSuccessResult("获取作业任务信息成功", jobTaskService.queryJobTask(jobTask));
    }

    /**
     * 新增作业任务的方法
     *
     * @param jobTask
     * @return
     */
    @YssPermissions(value = {"kettle:job:task:add"})
    @ApiOperation(value = "新增作业任务信息")
    @YssLog(module = "作业任务管理", remark = "新增作业任务信息")
    @RequestMapping(value = "/addJobTask")
    @ResponseBody
    public RestResult addJobTask(JobTask jobTask) throws Exception {
        jobTask.setId(DateUtil.generateUUID());
        jobTask.setAddTime(LocalDateTime.now());
        jobTaskService.save(jobTask);
        return ResultGenerator.getSuccessResult("新增作业任务信息成功！");
    }

    /**
     * 修改作业任务信息
     *
     * @return
     */
    @YssPermissions(value = {"kettle:job:task:edit"})
    @ApiOperation(value = "修改作业任务信息")
    @YssLog(module = "作业任务管理", remark = "修改作业任务信息")
    @RequestMapping(value = "/editJobTask")
    @ResponseBody
    public RestResult editJobTask(JobTask jobTask) throws Exception {
        if (jobTask == null || StringUtils.isBlank(jobTask.getId())) {
            throw new BusinessException("获取作业任务信息失败，请稍后重试！");
        }
        jobTask.setEditTime(LocalDateTime.now());
        jobTaskService.updateById(jobTask);
        return ResultGenerator.getSuccessResult("修改作业任务信息成功！");
    }

    /**
     * 删除作业任务信息
     *
     * @return
     */
    @YssPermissions(value = {"kettle:job:task:del"})
    @ApiOperation(value = "删除作业任务信息")
    @YssLog(module = "作业任务管理", remark = "删除作业任务信息")
    @RequestMapping(value = "/delJobTask")
    @ResponseBody
    public RestResult delJobTask(String ids) throws Exception {
        if (StringUtils.isBlank(ids)) {
            throw new BusinessException("获取删除作业任务信息失败，请稍后重试！");
        }
        List<String> list = JSONArray.parseArray(ids, String.class);
        jobTaskService.removeByIds(list);
        QueryWrapper<JobTaskDetails> wrapper = new QueryWrapper<>();
        wrapper.in("TASK_ID", list);
        jobTaskDetailsService.remove(wrapper);
        // 行删除改任务的所有依赖关系
        QueryWrapper<JobRelation> wrapperRelation = new QueryWrapper<>();
        wrapperRelation.in("TASK_ID", ids);
        jobRelationService.remove(wrapperRelation);
        return ResultGenerator.getSuccessResult("删除作业任务信息成功！");
    }
}
